package com.fiberhome.boot.utils;

import java.io.IOException;

import org.lokra.seaweedfs.core.FileSource;
import org.lokra.seaweedfs.core.FileTemplate;
import org.lokra.seaweedfs.core.file.FileHandleStatus;
import org.springframework.web.multipart.MultipartFile;


public class SeaweedClient {

	private String host;
	
	private int port;
	
	private FileTemplate template;
	
	public SeaweedClient(String host,int port){
		this.host = host;
		this.port = port;
		init();
	}
	
	public void init(){
		FileSource fileSource = new FileSource();
		fileSource.setHost(host);
		fileSource.setPort(port);
		try {
			fileSource.startup();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		template = new FileTemplate(fileSource.getConnection());
	}
	
	public SeaweedResponse saveFile(MultipartFile file) throws IOException{
		SeaweedResponse response = new SeaweedResponse();
		String fileName = file.getOriginalFilename();
		FileHandleStatus status = template.saveFileByStream(fileName, file.getInputStream());
        if(status!=null){
        	response.setFileId(status.getFileId());
        	response.setFilePath(template.getFileUrl(status.getFileId()));
        	response.setFileName(fileName);
        }
        return response;
	}
	
	public String getFile(String fileId) throws IOException{
		return template.getFileUrl(fileId);
	}
}
